package dnl.persistence;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

public class JdbcToolz {

	public static boolean tableExists(String tableName, Connection connection) throws SQLException {
		Set<String> existingTableNames = getExistingTableNames(connection, false);
		return existingTableNames.contains(tableName);
	}

	public static Set<String> getExistingTableNames(Connection connection, boolean full) throws SQLException {
		Set<String> tableNames = new HashSet<>();
		DatabaseMetaData metaData = connection.getMetaData();
		ResultSet res = metaData.getTables(null, null, null, new String[] { "TABLE" });
		while (res.next()) {
			String schema = res.getString("TABLE_SCHEM");
			String tableName = res.getString("TABLE_NAME");
			if (full) {
				tableNames.add(schema + "." + tableName);
			} else {
				tableNames.add(tableName);
			}
		}
		return tableNames;
	}

	public static TableInfo getTableInfo(Connection connection, String tableName) throws SQLException {
		DatabaseMetaData metaData = connection.getMetaData();
		ResultSet rs = metaData.getColumns(null, null, tableName, null);
        TableInfo ti = new TableInfo(tableName);

        while (rs.next()) {
            String name = rs.getString("COLUMN_NAME");
            String type = rs.getString("TYPE_NAME");
            int ordinal = rs.getInt("ORDINAL_POSITION");
            ti.addColumnInfo(name, SqlType.valueOf(type), ordinal);
        }
		return ti;
	}

	public static void createTable(Connection connection, TableInfo tableInfo) {

	}

	public static void createTable(Connection connection, String sql) throws SQLException {
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		preparedStatement.execute();
	}
}
